#!/usr/bin/python
# coding=utf-8
import requests
import time
import json
import csv
import smtplib
from email.mime.text import MIMEText
#设置服务器所需信息
#163邮箱服务器地址
mail_host = 'smtp.163.com'
#163用户名
mail_user = '17771420231@163.com'
#密码(部分邮箱为授权码)
mail_pass = 'wangliang1'
#邮件发送方邮箱地址
sender = '17771420231@163.com'
#邮件接受方邮箱地址，注意需要[]包裹，这意味着你可以写多个邮件地址群发
# receivers = ['648917857@qq.com','339003672@qq.com']
receivers = ['339003672@qq.com']
# receivers = ['648917857@qq.com']
#设置email信息
#邮件内容设置
message = MIMEText('牢记规则，勿贪多','plain','utf-8')
#邮件主题
message['Subject'] = '出现挂'
#发送方信息
message['From'] = sender
#接受方信息
message['To'] = receivers[0]
origin = []
while True:
    try:
        res = requests.get("https://47927.com/ajax/ajax_getapi.php?type=pk10&a=1", verify=False)
        try:
            data = json.loads(res.content)
        except:
            continue
        data = data['APICode']
        num = 0
        for d in data:
            num = num + 1
            if num == 15:
                time.sleep(60)
                break

            if d in origin:
                continue
            print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
            print(d)
            with open('origin.csv', 'a', newline='', encoding='gb18030') as csvout:
                rows = [];
                origin.append(d)
                if len(origin) == 20:
                    origin.pop(0)
                rows.append(str(time.time()))
                rows.append(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
                for (k, v) in d.items():
                    if v == "挂":
                        try:
                            # smtpObj = smtplib.SMTP()
                            # 连接到服务器
                            # smtpObj.connect(mail_host, 25)
                            # 登录到服务器
                            smtpObj = smtplib.SMTP_SSL(mail_host, 465)
                            smtpObj.login(mail_user, mail_pass)
                            # 发送
                            smtpObj.sendmail(
                                sender, receivers, message.as_string())
                            # 退出
                            smtpObj.quit()
                        except smtplib.SMTPException as e:
                            print('error', e)  # 打印错误
                    rows.append(v)

                wcsv = csv.writer(csvout)
                wcsv.writerow(rows)
    except:
        continue



